package com.xjd.edu.user.controller.login.auth;

import com.google.common.collect.Lists;
import com.xjd.edu.common.enums.AdminStatus;
import com.xjd.edu.common.enums.HostTypeEnum;
import com.xjd.edu.common.enums.RedisKeyEnum;
import com.xjd.edu.common.exception.LoginException;
import com.xjd.edu.common.model.login.LoginModel;
import com.xjd.edu.common.model.login.LoginResult;
import com.xjd.edu.common.utils.DesensitizedUtil;
import com.xjd.edu.common.utils.GenIdUtil;
import com.xjd.edu.toolkit.cache.GameRedisTemplate;
import com.xjd.edu.user.entity.admin.SysUser;
import com.xjd.edu.user.service.admin.SysUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zsw
 * @description:
 * @date 2021-01-14 18:03:09
 */
@Component
@Slf4j
public class PipiAdminAuthentication extends AbsAuthentication {

    private static final String SESSION_CAPTCHA = "captcha";
    private static final int LOGIN_EXPIRE = 60 * 60;

    @Autowired
    private GameRedisTemplate gameRedisTemplate;

    @Autowired
    private SysUserService sysUserService;

    @Value("${config.evn.prefix}")
    private String pre;

    @Override
    public List<HostTypeEnum> type() {
        return Lists.newArrayList(HostTypeEnum.PIPI_ADMIN);
    }

    @SneakyThrows
    @Override
    public LoginResult login(LoginModel loginModel, HostTypeEnum hostTypeEnum) {

        String password = loginModel.getPassword();
        String username = loginModel.getUsername();
        String code = loginModel.getCode();
        int times = 0;
        //password = Base64.decodeStr(password);
        String timesStr = (String) gameRedisTemplate.get(generateKey(RedisKeyEnum.ADMIN_CAPTCHA_TIMES, username)).orElse(null);
        if (timesStr != null) {
            times = Integer.parseInt(timesStr);
        }
        if (times >= 3) {
            String captcha = (String) gameRedisTemplate.get(SESSION_CAPTCHA).orElse(null);
            log.info("用户验证码code:{}", code);
            log.info("服务器验证码sessionCode:{}", captcha);
            // 判断验证码
            if (code == null || !code.trim().equalsIgnoreCase(captcha)) {
                throw new LoginException(LoginException.ExceptionCode.VERIFY_CODE_ERROR);
            }
        }
        if (times >= 10) {
            throw new LoginException(LoginException.ExceptionCode.ADMIN_LOGIN_LIMIT);
        }

        //通过username从数据库中查找 User对象，如果找到，没找到.
        SysUser admin = sysUserService.selectUserByUserName(username);
        log.info("adminInfo=" + admin);
        if (admin == null) {
            throw new LoginException(LoginException.ExceptionCode.ADMIN_NOT_EXITS);
        }
        if (AdminStatus.DISABLE.getType().equals(admin.getStatus())) {
            throw new LoginException(LoginException.ExceptionCode.ADMIN_FORBID);
        }
        /*String salt = admin.getSalt();
        Password paramPassword = EncryptUtil.PiecesEncode(password, salt);

        log.info("decodePass:{},param pass:{},dbPass:{}", password, paramPassword, admin.getPassword());

        if (!Objects.equals(admin.getPassword(), paramPassword.getPassword())) {
            throw new LoginException(LoginException.ExceptionCode.ADMIN_PASSWORD_NOT_MATCH);
        }*/
        /*if (!Objects.equals(admin.getPassword(), password)) {
            throw new LoginException(LoginException.ExceptionCode.ADMIN_PASSWORD_NOT_MATCH);
        }*/

        admin.setPassword(null);
        //admin.setSalt(null);
        Map<String, Object> adminMap = new HashMap<>();
        adminMap.put("id", admin.getUserId());
        adminMap.put("name", admin.getUserName());
        adminMap.put("username", admin.getUserName());
        adminMap.put("status", admin.getStatus());
        String token = GenIdUtil.GetToken();
        gameRedisTemplate.hmset(generateKey(RedisKeyEnum.ADMIN_TOKEN, token), adminMap, Duration.ofSeconds(LOGIN_EXPIRE));


        LoginResult result = new LoginResult();
        BeanUtils.copyProperties(admin, result);
        result.setToken(token);
        gameRedisTemplate.del(generateKey(RedisKeyEnum.ADMIN_TOKEN, username));
        result.setMobile(DesensitizedUtil.mobilePhone(result.getMobile()));
        return result;
    }

    public String generateKey(RedisKeyEnum redisKeyEnum, String id) {
        return pre + RedisKeyEnum.SPLIT + redisKeyEnum.name() + RedisKeyEnum.SPLIT + id;
    }
}
